//
//  LoginViewController.m
//  digitalCurrency
//
//  Created by sunliang on 2018/1/29.
//  Copyright © 2018年 ZhengTuo. All rights reserved.
//

#import "LoginViewController.h"
#import "ForgetViewController.h"
#import "ZTRegisterViewController.h"
#import "CYForgetViewController.h"
#import "CYBindPhoneViewController.h"

@interface LoginViewController ()<UITextFieldDelegate, TencentSessionDelegate, WXApiDelegate>
{
    NSInteger _countDown;
    NSTimer *_timer;
}
@property(nonatomic,copy)NSString *dbPath;//存入数据库的路径
@property(nonatomic,assign)NSInteger sqliteFlag;//判断是否存入
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewTopConstraint;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *codeOrPasswordTF;
@property (weak, nonatomic) IBOutlet UIImageView *leftImageView;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *codeBtnWidthConstraint;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backViewHeightConstraint;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (weak, nonatomic) IBOutlet UIButton *registeBtn;

@property (weak, nonatomic) IBOutlet UIView *codeView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *codeViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *codeViewMarginTopConstraint;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *passwordHeightConstraint;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *passwordViewMarginTopConstraint;

@property (weak, nonatomic) IBOutlet UIButton *forgetPasswordBtn;
@property (weak, nonatomic) IBOutlet UIButton *changeCodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *eyeBtn;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;

@property (nonatomic, strong) TencentOAuth *tencentOAuth;
@property (weak, nonatomic) IBOutlet UIButton *qqBtn;
@property (weak, nonatomic) IBOutlet UIButton *wechatBtn;

@end

@implementation LoginViewController

- (void)dealloc{
    [_timer invalidate];
    _timer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wxLogin" object:nil];
}
- (IBAction)forgetAction:(UIButton *)sender {
    CYForgetViewController *forget = [[CYForgetViewController alloc] init];
    [[AppDelegate sharedAppDelegate] pushViewController:forget];
}

- (IBAction)registeActoin:(UIButton *)sender {
    ZTRegisterViewController *regist = [[ZTRegisterViewController alloc] init];
    [[AppDelegate sharedAppDelegate] pushViewController:regist];
}

- (IBAction)getCodeAction:(UIButton *)sender {
    
    //先判断手机号
    if (self.phoneTF.text.length <= 0) {
        [self.view makeToast:@"请输入您的手机号" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    [self getVerify];
}

- (void)getVerify{
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"code"];
    NSDictionary *param = @{@"phone":self.phoneTF.text};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"验证码 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
            self.codeBtn.enabled = YES;
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                self->_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                
            }else{
                self.codeBtn.enabled = YES;
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

#pragma mark - PrivateMethod
- (void)onTimer{
    if (_countDown > 0) {
        [self.codeBtn setTitle:[NSString stringWithFormat:@"%ld秒重新获取", (long)_countDown] forState:UIControlStateNormal];
        _countDown--;
    }else{
        _countDown = 60;
        [_timer invalidate];
        _timer = nil;
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.codeBtn.enabled = YES;
    }
}


- (IBAction)loginAction:(UIButton *)sender {
    if ([NSString stringIsNull:self.phoneTF.text]) {
        [self.view makeToast:@"请输入手机号" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    NSString *url = @"";
    NSDictionary *param = @{};

    if (self.changeCodeBtn.selected) {
        //
        if ([NSString stringIsNull:self.passwordTF.text]) {
            [self.view makeToast:@"请输入密码" duration:1.5 position:CSToastPositionCenter];
            return;
        }
        url = [NSString stringWithFormat:@"%@%@",User_HOST, @"loginByPhonePwd"];
        param = @{@"phone":self.phoneTF.text, @"password":self.passwordTF.text};
        
    }else{
        if ([NSString stringIsNull:self.codeOrPasswordTF.text]) {
            [self.view makeToast:@"请输入验证码" duration:1.5 position:CSToastPositionCenter];
            return;
        }
        url = [NSString stringWithFormat:@"%@%@",User_HOST, @"loginByPhone"];
        param = @{@"phone":self.phoneTF.text, @"captcha":self.codeOrPasswordTF.text};
        
    }
    
    [EasyShowLodingView showLoding];
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"登录 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];

        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSDictionary *data = responseResult[@"data"];
                [YLUserInfo getuserInfoWithDic:data];
                
                NSUserDefaults *us = [NSUserDefaults standardUserDefaults];
                [us setObject:self.phoneTF.text forKey:UserPhone];
                [us synchronize];
                [[AppDelegate sharedAppDelegate] popToRootViewController];
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];

            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (IBAction)chageLoginTypeAction:(UIButton *)sender {
    self.changeCodeBtn.selected = !self.changeCodeBtn.selected;
    if (!self.changeCodeBtn.selected) {
        //短信登录
        self.codeView.hidden = NO;
        self.codeViewHeightConstraint.constant = 45;
        self.codeViewMarginTopConstraint.constant = 15;
        
        self.passwordView.hidden = YES;
        self.passwordViewMarginTopConstraint.constant = 0;
        self.passwordHeightConstraint.constant = 0;
        self.forgetPasswordBtn.hidden = YES;
    }else{
        //密码登录
        self.codeView.hidden = YES;
        self.codeViewHeightConstraint.constant = 0;
        self.codeViewMarginTopConstraint.constant = 0;
        
        self.passwordView.hidden = NO;
        self.passwordViewMarginTopConstraint.constant = 15;
        self.passwordHeightConstraint.constant = 45;
        self.forgetPasswordBtn.hidden = NO;
    }
}

- (IBAction)qqLoginAction:(UIButton *)sender {
    //QQ或者TIM已安装
    if ([QQApiInterface isQQInstalled] && [QQApiInterface isQQSupportApi]) {
        NSArray* permissions = [self getPermissions];
        //授权列表数组 根据实际需要添加
        self.tencentOAuth = [[TencentOAuth alloc]initWithAppId:@"101498694" andDelegate:self];
        self.tencentOAuth.redirectURI = @"";
        self.tencentOAuth.authShareType = AuthShareType_QQ;
        [self.tencentOAuth authorize:permissions inSafari:NO];
        
    }

}

#pragma mark --------- qq登录状态回调 ------

//登录完成后，会调用TencentSessionDelegate中关于登录的协议方法。

- (void)tencentDidLogin

{
    NSLog(@"qq登录完成");
    
    if (self.tencentOAuth.accessToken && 0 != [self.tencentOAuth.accessToken length])
        
    {
        //  记录登录用户的OpenID、Token以及过期时间
        
        NSLog(@"token===%@",[_tencentOAuth accessToken] );
        
        NSLog(@"openId===%@",[_tencentOAuth openId]) ;//这个是用户的唯一id,使用它来登录自己的服务器
        NSLog(@"appid === %@",[_tencentOAuth appId]);
        
        [self getQQUserInfo];//自己实现的方法，得到用户信息，见下一步说明。
        [self LoginWithQQAcessToken:[_tencentOAuth accessToken]];
    }
    else{
//        _labelAccessToken.text = @"登录不成功没有获取accesstoken";
    }
    
}

//非网络错误导致登录失败：

-(void)tencentDidNotLogin:(BOOL)cancelled
{
    NSLog(@"非网络错误导致登录失败");
    if (cancelled)
    {
        NSLog(@"用户取消登录操作");
    }
    else{
    }
}

//网络错误导致登录失败：

-(void)tencentDidNotNetWork
{
    NSLog(@"网络错误导致登录失败：");
}

#pragma mark ---------- 获取qq用户信息 ----

- (void)getQQUserInfo {
    if(![_tencentOAuth getUserInfo]){
        NSLog(@"获取qq用户信息失败");
    }
}

//获取用户信息结束回调
#pragma mark -------- qq用户信息回调 -------
/**
 
 * Called when the get_user_info has response.
 
 */
- (void)getUserInfoResponse:(APIResponse*) response {
    if (response.retCode ==URLREQUEST_SUCCEED)
    {
        NSMutableString *str=[NSMutableString stringWithFormat:@""];
        for (id key in response.jsonResponse) {
            
            [str appendString: [NSString stringWithFormat:@"%@:%@\n",key,[response.jsonResponse objectForKey:key]]];
        }
        NSLog(@"%@",str);
        NSString* url = [[NSString alloc]initWithString:[response.jsonResponse objectForKey:@"figureurl_qq_2"]];
        NSString* nickname = [[NSString alloc] initWithString:[response.jsonResponse objectForKey:@"nickname"]];
        if ([NSString stringIsNull:url] || [NSString stringIsNull:nickname]) {
            NSLog(@"获取qq用户信息失败");
        }else{
//            NSNumber* typeQQ = [NSNumber numberWithInteger:1];
//            [self login:self.openIDandNickname:nicknameandAvatar:url andType:typeQQ];//自己的登录函数
        }
    }
    else{
        [self.view makeToast:response.errorMsg duration:1.5 position:CSToastPositionCenter];
    }
    
}

- (void)LoginWithQQAcessToken:(NSString *)acesstoken{
    [EasyShowLodingView showLoding];
    [[XBRequest sharedInstance] postDataWithUrl:[NSString stringWithFormat:@"%@%@",User_HOST, @"third/qq"] Parameter:@{@"accessToken":acesstoken} ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"qq登录 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
            
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
//                NSDictionary *data = responseResult[@"data"];
//                [YLUserInfo getuserInfoWithDic:data];
//
//                NSUserDefaults *us = [NSUserDefaults standardUserDefaults];
//                [us setObject:self.phoneTF.text forKey:UserPhone];
//                [us synchronize];
//                [[AppDelegate sharedAppDelegate] popViewController];
//                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                NSDictionary *data = responseResult[@"data"];
                if (![data[@"phone"] isKindOfClass:[NSString class]]) {
                    CYBindPhoneViewController *bind = [[CYBindPhoneViewController alloc] init];
                    bind.token = data[@"token"];
                    [[AppDelegate sharedAppDelegate] pushViewController:bind];
                }else{
                    [self getUserInfosWithToken:data[@"token"]];
                }
                
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

#pragma mark - 获取用户信息
- (void)getUserInfosWithToken:(NSString *)token{
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"userInfo"];
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 2.设置非校验证书模式
    sessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    sessionManager.securityPolicy.allowInvalidCertificates = YES;
    [sessionManager.securityPolicy setValidatesDomainName:NO];
    
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    sessionManager.requestSerializer.timeoutInterval = 10.f;
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript",@"text/plain",@"image/png", nil];
    [sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"usertoken"];
    NSString *str = @"";
    if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_9_0) {
        str = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else{
        str = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    
    [sessionManager GET:str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [EasyShowLodingView hidenLoding];
        
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDic = (NSDictionary *)result;
            if ([resultDic[Response_code] integerValue] == Response_value) {
                NSDictionary *data = resultDic[@"data"];
                NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:data];
                [muDic setObject:token forKey:@"token"];
                [YLUserInfo getuserInfoWithDic:muDic];
                NSUserDefaults *us = [NSUserDefaults standardUserDefaults];
                [us setObject:self.phoneTF.text forKey:UserPhone];
                [us synchronize];
                [[AppDelegate sharedAppDelegate] popToRootViewController];
            }else{
                
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EasyShowLodingView hidenLoding];
        
    }];
}

- (NSMutableArray*)getPermissions{
    NSMutableArray * g_permissions = [[NSMutableArray alloc] initWithObjects:kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,nil];
    return g_permissions;
}


- (IBAction)wechatLoginAction:(UIButton *)sender {
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq* req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo"; // @"post_timeline,sns"
        req.state = @"wx_oauth_authorization_state";
//        req.openID = @"";
        [WXApi sendAuthReq:req viewController:self delegate:self];
    }
}

- (void)wxLogin:(NSNotification *)noti{
    [self wxLoginWithCode:noti.object];
}

- (void)wxLoginWithCode:(NSString *)code{
    [EasyShowLodingView showLoding];
    [[XBRequest sharedInstance] postDataWithUrl:[NSString stringWithFormat:@"%@%@",User_HOST, @"third/wx"] Parameter:@{@"code":code} contentType:@"application/x-www-form-urlencoded" ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"wx登录 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSDictionary *data = responseResult[@"data"];
                if ([NSString stringIsNull:data[@"phone"]]) {
                    CYBindPhoneViewController *bind = [[CYBindPhoneViewController alloc] init];
                    bind.token = data[@"token"];
                    [[AppDelegate sharedAppDelegate] pushViewController:bind];
                }else{
                    [self getUserInfosWithToken:data[@"token"]];
                }
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (IBAction)eyeAction:(UIButton *)sender {
    self.eyeBtn.selected = !self.eyeBtn.selected;
    self.passwordTF.secureTextEntry = !self.eyeBtn.selected;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _countDown = 60;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxLogin:) name:@"wxLogin" object:nil];

//    self.navigationItem.title=LocalizationKey(@"login");
    self.title = @"用户登录";
    if ([[NSUserDefaults standardUserDefaults] objectForKey:UserPhone]) {
        NSUserDefaults *us = [NSUserDefaults standardUserDefaults];
        self.phoneTF.text = [us objectForKey:UserPhone];
    }
    self.phoneTF.delegate = self;
    self.codeOrPasswordTF.delegate = self;
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.layer.cornerRadius = self.loginBtn.frame.size.height / 2;
    
    self.changeCodeBtn.selected = NO;
    //隐藏密码
    self.passwordView.hidden = YES;
    self.passwordViewMarginTopConstraint.constant = 0;
    self.passwordHeightConstraint.constant = 0;
    self.forgetPasswordBtn.hidden = YES;
    
    //检测是否安装qq和微信
    if (![WXApi isWXAppInstalled]) {
        self.wechatBtn.hidden = YES;
        self.wechatBtn.userInteractionEnabled = NO;
    }
    if (![TencentOAuth iphoneQQInstalled]) {
        self.qqBtn.hidden = YES;
        self.qqBtn.userInteractionEnabled = NO;
    }
}

- (void)updateViewConstraints{
    [super updateViewConstraints];
    self.backViewHeightConstraint.constant = CGRectGetMaxY(self.view.frame) + 10;
    self.scrollViewTopConstraint.constant = - Height_NavBar;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.phoneTF) {
        NSString *resultStr = [self.phoneTF.text stringByReplacingCharactersInRange:range withString:string];
        if (resultStr.length == 12) {
            return NO;
        }
    }
    
    if (textField == self.codeOrPasswordTF) {
        NSString *resultStr = [self.codeOrPasswordTF.text stringByReplacingCharactersInRange:range withString:string];
        if (resultStr.length == 16) {
            return NO;
        }
    }
    return YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //设置导航栏透明
    [self.navigationController.navigationBar setTranslucent:true];
    //把背景设为空
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //处理导航栏有条线的问题
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    attributes[NSFontAttributeName] = [UIFont boldSystemFontOfSize:17];
    attributes[NSForegroundColorAttributeName] = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(popAction)];
}

- (void)popAction{
    [[AppDelegate sharedAppDelegate] popViewController];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setTranslucent:NO];
    
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    attributes[NSFontAttributeName] = [UIFont boldSystemFontOfSize:17];
    attributes[NSForegroundColorAttributeName] = [UIColor blackColor];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
}


@end
